package com.zige.zige.dialog;

import android.app.DialogFragment;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.util.Base64;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.qiniu.android.http.ResponseInfo;
import com.qiniu.android.storage.UpCompletionHandler;
import com.qiniu.android.storage.UploadManager;
import com.zige.zige.LittleZebraApplication;
import com.zige.zige.R;
import com.zige.zige.activity.PersonalInformationActivity;
import com.zige.zige.constants.UrlConsts;
import com.zige.zige.task.PostRequestTask;
import com.zige.zige.task.TaskExecutor;
import com.zige.zige.utils.BitmapCompressor;
import com.zige.zige.utils.DateUtils;
import com.zige.zige.utils.NetworkUtils;
import com.zige.zige.utils.SharedPreferencesUtils;
import com.zige.zige.utils.ToastUtils;

import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;

/**
 * Created by Kim-wu on 2015/8/20.
 * 上传头像的两种选择方式
 */
public class UploadPictureDialog extends DialogFragment implements View.OnClickListener {

    private TextView tv_taking_pictures, tv_photo_album, tv_cannel;

    PersonalInformationActivity activity;
    public LittleZebraApplication application;

    private UpCompletionHandler completionHandler;
    private  File img;

    ProgressDialog waitingDialog;

    private String headImageUrl;

    public interface UploadPictureDialogListener
    {
        void OnUploadPictureDialogInputComplete(String headImageUrl,String headImagePath);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activity = (PersonalInformationActivity) getActivity();
        application = (LittleZebraApplication)LittleZebraApplication.getInstance();
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
        View view = inflater.inflate(R.layout.dialog_uploadpicture, container);
        setStyle(DialogFragment.STYLE_NORMAL, R.style.shareDialog_style);
        Window window = getDialog().getWindow();
        window.setGravity(Gravity.BOTTOM);
        window.setBackgroundDrawable(new ColorDrawable(0xffffffff));
        WindowManager.LayoutParams lp = getDialog().getWindow().getAttributes();
        lp.alpha = 1.0f; // 透明度
        window.setAttributes(lp);
        getDialog().show();
        initView(view);
        return view;
    }

    private void initView(View view) {
        tv_taking_pictures = (TextView) view.findViewById(R.id.tv_taking_pictures);
        tv_taking_pictures.setOnClickListener(this);
        tv_photo_album = (TextView) view.findViewById(R.id.tv_photo_album);
        tv_photo_album.setOnClickListener(this);
        tv_cannel = (TextView) view.findViewById(R.id.tv_cannel);
        tv_cannel.setOnClickListener(this);

    }

    private static int CAMERA_REQUEST_CODE = 1;
    private static int GALLERY_REQUEST_CODE = 2;
    private static int CROP_REQUEST_CODE = 3;

    @Override
    public void onClick(View v) {

        switch (v.getId()) {

            case R.id.tv_taking_pictures:
                Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(captureIntent, CAMERA_REQUEST_CODE);
                break;
            case R.id.tv_photo_album:
                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                intent.setType("image/*");
                startActivityForResult(intent, GALLERY_REQUEST_CODE);
                break;
            case R.id.tv_cannel:
                getDialog().dismiss();
                break;
        }

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CAMERA_REQUEST_CODE) {
            if (data == null) {
                return;
            }
            Bundle extras = data.getExtras();
            if (extras != null) {
                Bitmap bm = extras.getParcelable("data");
                Uri uri = saveBitmap(bm);
                startImageZoom(uri);
            }
        } else if (requestCode == GALLERY_REQUEST_CODE) {
            if (data == null) {
                return;
            }
            Uri uri;
            uri = data.getData();
            Uri fileUri = convertUri(uri);
            startImageZoom(fileUri);
        } else if (requestCode == CROP_REQUEST_CODE) {
            if (data == null) {
                return;
            }
            Bundle extras = data.getExtras();
            if (extras == null) {
                return;
            }
            Bitmap bm = extras.getParcelable("data");
            getQiNiuToken();

            if (waitingDialog != null)
                waitingDialog.show();
            else {
                waitingDialog = new ProgressDialog(activity);
                waitingDialog.setMessage("正在保存...");
                waitingDialog.setCancelable(false);
                waitingDialog.show();
            }


            SharedPreferencesUtils.saveValue(activity,SharedPreferencesUtils.user_loaclheadimage,headImageUrl);
            dismiss();
        }
    }

    private Uri saveBitmap(Bitmap bm) {
        File tmpDir = new File(Environment.getExternalStorageDirectory() + "/Littlezebra/video");
        if (!tmpDir.exists()) {
            tmpDir.mkdir();
        }
        img = new File(tmpDir, DateUtils.getNowTimeStamp()+"head.png");

        UploadPictureDialogListener listener = (UploadPictureDialogListener) getActivity();
        Log.e("wu","3333344455555");
        listener.OnUploadPictureDialogInputComplete(getFileName(String.valueOf(img)),String.valueOf(img));
        Log.e("wu","headImageUrl+ooooo  "+getFileName(String.valueOf(img)));
        try {
            FileOutputStream fos = new FileOutputStream(img);
            Bitmap bitmap = BitmapCompressor.decodeSampledBitmapFromBitmap(bm,400,480);
            bitmap.compress(Bitmap.CompressFormat.PNG, 60, fos);

            fos.flush();
            fos.close();
            return Uri.fromFile(img);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

    }

    private Uri convertUri(Uri uri) {
        InputStream is = null;
        try {
            is = activity.getContentResolver().openInputStream(uri);
            Bitmap bitmap = BitmapFactory.decodeStream(is);
            is.close();
            return saveBitmap(bitmap);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return null;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    private void startImageZoom(Uri uri) {
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, CROP_REQUEST_CODE);
    }



    /**
     * 获取七牛token
     */

    private void getQiNiuToken() {
//        final String videoImage = getFileName(String.valueOf(img));
        final String imageName = getFileName(String.valueOf(img));
        Log.e("wu","zzzzz   "+imageName);
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("fileKey", imageName);

        TaskExecutor.getInstance().execute(new PostRequestTask(params, activity, UrlConsts.GET_QINIU_TOKEN) {
            @Override
            protected void handleResponse(String response) {
                try {
                    JSONObject object = new JSONObject(response);
                    int code = object.getInt("code");
                    if (code == 0000) {
                        String  qiNiuToken = object.getString("qiniuToken");
                        UploadManager uploadManager = new UploadManager();
                        uploadManager.put(img, imageName, qiNiuToken, new UpCompletionHandler() {
                            @Override
                            public void complete(String s, ResponseInfo responseInfo, JSONObject jsonObject) {
                                if(200==responseInfo.statusCode){
                                    SharedPreferencesUtils.saveValue(activity,SharedPreferencesUtils.user_loaclheadimage,"");

                                    String imageName = getFileName(String.valueOf(img));

                                    if (waitingDialog != null && waitingDialog.isShowing())
                                        waitingDialog.dismiss();
                                        application.getUserInfo().locadHeadUrl = getQniuImageUrl(imageName);
                                    /**头像地址*/
                                    headImageUrl = getQniuImageUrl(imageName);


                                }else {
                                    ToastUtils.showToast(getActivity(),"上传失败");
                                    if (waitingDialog != null && waitingDialog.isShowing())
                                        waitingDialog.dismiss();

                                }
                            }
                        }, null);

                        SharedPreferencesUtils.saveValue(getActivity(),SharedPreferencesUtils.user_loaclheadimage,img);
                    } else {
                        ToastUtils.showToast(activity, "网络异常，上传失败");
                        waitingDialog.dismiss();
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }

            }
        });
    }



    private void sendImage(Bitmap bm) {
        if (NetworkUtils.isNetworkAvailable(getActivity())) {
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bm.compress(Bitmap.CompressFormat.PNG, 100, stream);
            byte[] bytes = stream.toByteArray();
            String img = new String(Base64.encodeToString(bytes, Base64.DEFAULT));
            HashMap<String, String> params = new HashMap<>();
//            params.put("token", application.getUserInfo().token);
            params.put("imgStr", img);
            TaskExecutor.getInstance().execute(new PostRequestTask(params, activity, null) {
                @Override
                protected void handleResponse(String response) {
                    try {
                        JSONObject obj = new JSONObject(response);
                        int ret = obj.getInt("Ret");
                        String msg = obj.getString("Msg");
                        if (ret == 0) {
                            ToastUtils.showToast(activity,"上传成功");
                            obj = obj.getJSONObject("Data");
                            String imgUrl = obj.getString("ShowUserHeadImgUrl");
                            application.getUserInfo().headPortraitUrl = imgUrl;
                            dismiss();
                        } else {
                            throw new Exception(msg);
                        }
                    } catch (Exception e) {
                        ToastUtils.showToast( activity,e.getMessage());
                    }
                }

                @Override
                protected void handleError() {
                    super.handleError();
                }
            });
        }else {
//            startActivity(new Intent(getActivity(), NetErrorActivity.class));
        }
    }

    public String getFileName(String pathandname){

        int start=pathandname.lastIndexOf("/");
        int end=pathandname.lastIndexOf(".");
        if(start!=-1 && end!=-1){
            return pathandname.substring(start+1,end);
        }else{
            return null;
        }

    }

    private String getQniuImageUrl(String name) { //http://7niudomain/littlezebra1924433291
        return "http://" + "7xkpsq.com2.z0.glb.qiniucdn.com" + "/" + name;
    }
}

